package com.flute.tools.xml.xpath;

import java.util.HashMap;

public class SplitedGroupPathNode implements IPathNode {
	private IPathNode group;
	private IPathNode innerGroup;
	private String spliter;
	private IPathNode pathNode;

	public IPathNode getGroup() {
		return group;
	}

	public void setGroup(IPathNode group) {
		this.group = group;
	}

	public IPathNode getInnerGroup() {
		return innerGroup;
	}

	public void setInnerGroup(IPathNode innerGroup) {
		this.innerGroup = innerGroup;
	}

	public String getSpliter() {
		return spliter;
	}

	public void setSpliter(String spliter) {
		this.spliter = spliter;
	}

	public IPathNode getPathNode() {
		return pathNode;
	}

	public void setPathNode(IPathNode pathNode) {
		this.pathNode = pathNode;
	}

	@Override
	public IPathNode fromPathString(String path) throws XmlPathException {
		SplitedGroupPathNode node = null;
		if (path != null) {
			String[] ps = path.split(GroupElementPathNode.SPLITER);

			if (ps.length == 4) {
				node = new SplitedGroupPathNode();
				node.group = PathParsers.getInstance().parse(ps[0]);
				node.innerGroup = PathParsers.getInstance().parse(ps[1]);
				node.spliter = ps[2].trim();
				node.pathNode = PathParsers.getInstance().parse(ps[3]);
			}
		}
		return node;
	}

	@Override
	public String toPathString() {
		return group.toPathString() + GroupElementPathNode.SPLITER
				+ innerGroup.toPathString() + GroupElementPathNode.SPLITER
				+ spliter + GroupElementPathNode.SPLITER
				+ pathNode.toPathString();
	}

	@Override
	public PathNodes[] divider(PathNodes nodes) {
		HashMap<String, PathNodes> map = new HashMap<String, PathNodes>();

		for (IPathNode node : nodes.getPathNodes()) {
			if (node instanceof SplitedGroupPathNode) {
				SplitedGroupPathNode gepn = (SplitedGroupPathNode) node;
				String key = gepn.getGroup().toPathString() + ":"
						+ gepn.getInnerGroup().toPathString();
				if (!map.containsKey(key)) {
					map.put(key, new PathNodes());
				}

				map.get(key).addPathNode(gepn);
			}
		}

		return map.values().toArray(new PathNodes[] {});
	}

}
